<template>
	<div class="contest-table" v-if="contest">
		<table class="table table-hover">
			<thead>
				<tr>
					<th>{{ $t('rank') }}</th>
					<th>{{ $t('user.name') }}</th>
					<th>{{ $t('user.nick') }}</th>
					<th>{{ $t('accepted') }}</th>
					<th>{{ $t('penalty') }}</th>

					<th v-for="index in contest.problemCount">
						{{ String.fromCharCode(64 + index) }}
					</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="item in rank" :key="item.rank">
					<td>{{ item.ranking }}</td>
					<td>
						<RouterLink class="link-color" :to="'/user/' + item.userId + '/info'">
							{{ item.usernick }}
						</RouterLink>
					</td>
					<td>{{ item.username }}</td>
					<td>{{ item.solved }}</td>
					<td>{{ item.penalty }}</td>

					<td v-for="index in contest.problemCount" :class="(item.problems[index] || {}).class">
						{{ (item.problems[index] || {}).penaltyInfo }}
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</template>


<script type="module">
import { ContestService } from '@/common/common.object'


function processProblem(rank, bestMap) {
	const ACCEPTED = "bgc-lightgreen";
	const INCORRECT = "bgc-lightcoral";
	const WINNER = "bgc-green c-white";

	rank.forEach(item => {
		for (let key in item.problems) {
			const problem = item.problems[key];

			if (!problem.penalty) {
				if (problem.failureTimes) {
					problem.penaltyInfo = -problem.failureTimes;
					problem.class = INCORRECT;
				}

				continue;
			}



			let penaltyInfo = problem.penalty;

			if (problem.failureTimesBeforeSuccess) {
				penaltyInfo += `(-${problem.failureTimesBeforeSuccess})`;
			}

			problem.penaltyInfo = penaltyInfo;



			if (problem.penalty !== bestMap[key]) {
				problem.class = ACCEPTED;
			} else {
				problem.class = WINNER;
			}
		};
	});
}

export default {
	inject: ['contest'],
	data() {
		return {
			rank: null,
		};
	},
	created() {
		this.$changeTitle(`{{rank}} - ${this.contest.name}`);

		ContestService.getRank(this.contest.id).then(result => {
			if (result && result.length) {
				processProblem(result, this.contest.best);

				this.rank = Object.freeze(result);
			}
		});
	},
	methods: {
	}
}
</script>


<style scope>
table>tbody>tr {
	cursor: pointer !important;
}

table>thead>tr>th {
	border-top: none !important;
}
</style>
